//
//  UserDefaultsExtensions.swift
//  SwiftWeather
//
//  Created by shen on 2023/8/28.
//

import Foundation

enum UserDefaultsKeys {
    static let cities = "cities"
    static let timeInBackground = "timeInBackground"
}

extension UserDefaults {
    func saveCities(_ cities: [City]) {
        do {
            let data = try JSONEncoder().encode(cities)
            set(data, forKey: UserDefaultsKeys.cities)
        } catch {
            print(error.localizedDescription)
        }
    }

    func fetchCities() -> [City]? {
        guard let data = data(forKey: UserDefaultsKeys.cities) else {
            return nil
        }
        return try? JSONDecoder().decode([City].self, from: data)
    }

    func saveBackgroundModeEnteringTime(_ date: Date) {
        setValue(date, forKey: UserDefaultsKeys.timeInBackground)
    }

    func getBackgroundModeEnteringTime() -> Date? {
        object(forKey: UserDefaultsKeys.timeInBackground) as? Date
    }
}
